package com.ssyx;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName:CompletableFutureDemo1
 * Description:
 *
 * @Author kay
 * @Create 2024/5/17 10:57
 * @Version 1.0
 */
//多任务组合
//allOf：等待所有任务完成
//anyOf：只要有一个任务完成
public class CompletableFutureDemo5 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        //任务1执行结果：1024
        CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() ->{
            System.out.println(Thread.currentThread().getName()+"--begin..");

            int result = 1024;
            System.out.println("任务1:" + result);
            System.out.println(Thread.currentThread().getName()+"--end..");
            return result;
        },executorService);

        //任务2执行结果：2048
        CompletableFuture<Integer> futureB = CompletableFuture.supplyAsync(() ->{
            System.out.println(Thread.currentThread().getName()+"--begin..");
            int result = 2048;
            System.out.println("任务2:" + result);
            System.out.println(Thread.currentThread().getName()+"--end..");
            return result;
        },executorService);

        //任务3 在futureA和futureB执行完毕后,任务3才能执行
        CompletableFuture<Void> all = CompletableFuture.allOf(futureA,futureB);
        all.get();
        System.out.println("over....");

    }
}
